package st.business.tepth.business.user.busnumber.workholder.repair.work.content;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.DiagnoseBean;
import st.business.tepth.business.bean.OperationBean;
import st.business.tepth.business.bean.PartBean;
import st.business.tepth.business.bean.PartLocationBean;
import st.business.tepth.business.bean.PersonBean;
import st.business.tepth.business.bean.PickGoods;
import st.business.tepth.business.bean.PickGoodsWrapper;
import st.business.tepth.business.bean.PickNumberBean;
import st.business.tepth.business.bean.ProgramBean;
import st.business.tepth.business.bean.RepairTaskBean;
import st.business.tepth.business.event.AddProgramEvent;
import st.business.tepth.business.event.GoodsEvent;
import st.business.tepth.business.event.ReloadRepairWorkDataEvent;
import st.business.tepth.business.event.StartBrotherEvent;
import st.business.tepth.business.goodsorder.GoodsOrderDelegate;
import st.business.tepth.business.user.busnumber.workholder.adapter.TroubleAdapter;
import st.business.tepth.business.user.busnumber.workholder.adapter.TroubleCommonAdapter;
import st.business.tepth.business.user.busnumber.workholder.adapter.TroublePagerAdapter;
import st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter;
import st.business.tepth.business.user.busnumber.workholder.adapter.TroubleWorkPersonAdapter;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogActionChoose;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogConfirmProgram;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogContactOtherProgram;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogNumberSelect;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogPartChoose;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogPartLocationChoose;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogSearchTrouble;
import st.business.tepth.business.user.busnumber.workholder.repair.work.WorkDelegate;
import st.business.tepth.business.user.operationchoose.OperationChooseDelegate;
import st.business.tepth.config.ItemFields;
import st.business.tepth.manager.GlobalDataManager;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.core.util.utilcode.util.ScreenUtils;
import st.shadow.library.core.util.utilcode.util.ToastUtils;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;
import st.shadow.library.ui.indicator.magicindicator.MagicIndicator;
import st.shadow.library.ui.indicator.magicindicator.ViewPagerHelper;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.CommonNavigator;
import st.shadow.library.ui.recycler.MultipleItemEntity;

import static st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter.TYPE_CAN_NOT_EDIT;
import static st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter.TYPE_MANUAL_CONFIRM;
import static st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter.TYPE_MANUAL_UN_CONFIRM;
import static st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter.TYPE_RELEVANCE_UN_CONFIRM;
import static st.business.tepth.business.user.busnumber.workholder.adapter.TroubleProgramAdapter.TYPE_SYSTEM_RECOMMEND_UN_CONFIRM;


/**
 * @author zhangyu
 * @date 2019/1/22
 * 小修作业界面
 */
public class RepairDelegate extends MvpFragment<RepairPresenter>
        implements RepairContract.View {
    @BindView(R2.id.indicator)
    MagicIndicator mMagicIndicator;
    @BindView(R2.id.view_pager_trouble)
    ViewPager mViewPagerTrouble;
    @BindView(R2.id.tv_trouble_count)
    TextView mTvTroubleCount;
    @BindView(R2.id.recycler_view_person)
    RecyclerView mRecyclerViewPerson;
    @BindView(R2.id.recycler_view_common_trouble)
    RecyclerView mRecyclerViewCommonTrouble;
    @BindView(R2.id.layout_container)
    ConstraintLayout mLayoutContainer;
    @BindView(R2.id.tv_confirm)
    TextView mTvConfirm;
    @BindView(R2.id.recycler_view_work_program)
    RecyclerView mRecyclerViewWorkProgram;
    @BindView(R2.id.tv_trouble_work_program)
    TextView mTvWorkProgram;
    @BindView(R2.id.et_search_trouble)
    TextView mEtSearch;
    @BindView(R2.id.tv_common_trouble)
    TextView mTvCommonDiagnose;
    private TroubleCommonAdapter mCommonAdapter;
    private TroubleProgramAdapter mProgramAdapter;
    private TroubleWorkPersonAdapter mPersonAdapter;
    private int mCurrentTroubleIndex = 0;
    private OptionsPickerView pvCustomOptions;
    private DialogLoader mDialogLoader;
    private int mRepairId;
    private int mVehicleSeriesId;
    private int mRepairTaskId;
    private ViewPager.OnPageChangeListener mOnPageChangeListener;
    private TroublePagerAdapter mTroublePagerAdapter;
    private UiDelegate mUiDelegate;
    private int mOperationState;
    private int mStatus;
    private int mPosition;

    public static RepairDelegate newInstance(int repairId,
                                             int vehicleSeriesId,
                                             int operationState,
                                             int position) {
        Bundle bundle = new Bundle();
        bundle.putInt("repairId", repairId);
        bundle.putInt("position", position);
        bundle.putInt("vehicleSeriesId", vehicleSeriesId);
        bundle.putInt("operationState", operationState);
        RepairDelegate delegate = new RepairDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mRepairId = bundle.getInt("repairId");
            mVehicleSeriesId = bundle.getInt("vehicleSeriesId");
            mOperationState = bundle.getInt("operationState");
            mPosition = bundle.getInt("position");
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_user_work_trouble;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        EventBus.getDefault().register(this);
        initView();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initData();
    }

    private void initView() {
        //作业人
        mRecyclerViewPerson.setLayoutManager(new LinearLayoutManager(_mActivity,
                LinearLayoutManager.HORIZONTAL, false));
        //常见诊断
        mRecyclerViewCommonTrouble.setLayoutManager(new LinearLayoutManager(_mActivity,
                LinearLayoutManager.HORIZONTAL, false));
        mDialogLoader = new DialogLoader(_mActivity);
        ViewPagerHelper.bind(mMagicIndicator, mViewPagerTrouble);
        initProgramView();
    }

    //初始化作业方案布局（惰性）
    private void initProgramView() {
        mRecyclerViewWorkProgram.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerViewWorkProgram.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                if (entity != null) {
                    int type = entity.getItemType();
                    int id = view.getId();
                    if (id == R.id.tv_action) {
                        //动作
                        chooseAction(adapter, view, position);
                    } else if (id == R.id.tv_obj || id == R.id.tv_part_code) {
                        //零部件和编码
                        choosePart(adapter, view, position, true);
                    } else if (id == R.id.tv_count) {
                        //零部件数量
                        choosePartCount(adapter, view, position);
                    } else if (id == R.id.tv_materials || id == R.id.tv_materials_code) {
                        //耗材和编码
                        choosePart(adapter, view, position, false);
                    } else if (id == R.id.tv_materials_count) {
                        //耗材数量
                        chooseGoodsCount(adapter, view, position);
                    } else if (id == R.id.tv_place) {
                        //位置
                        choosePartLocation(adapter, view, position);
                    } else if (id == R.id.tv_delete) {
                        if (type == TYPE_MANUAL_UN_CONFIRM
                                || type == TYPE_SYSTEM_RECOMMEND_UN_CONFIRM
                                || type == TYPE_RELEVANCE_UN_CONFIRM) {
                            adapter.remove(position);
                            if (mUiDelegate != null) {
                                mUiDelegate.changeState();
                            }
                        }
                    }
                }
            }
        });
        mProgramAdapter = new TroubleProgramAdapter(_mActivity, null,
                new TroubleProgramAdapter.onItemOperatorListener() {

                    @Override
                    public void onOperator(final ProgramBean program, String status, final int position) {
                        mDialogLoader.showWarning(status, "请确认",
                                new IDialogClickListener() {
                                    @Override
                                    public void onClick() {
                                        int pickStatus = program.getPicking_status();
                                        if ((pickStatus >= 6 && pickStatus <= 9) ||
                                                pickStatus == 0) {
                                            //减去header
                                            deleteProgram(program, position - 1);
                                        } else if (pickStatus == 3 || pickStatus == 5) {
                                            //退料
                                            returnGoods(program, position - 1);
                                        }
                                    }
                                });
                    }
                }, new TroubleProgramAdapter.onItemOperatorListener() {
            @Override
            public void onOperator(final ProgramBean program, String status, final int position) {
                //添加共同作业人
                mDialogLoader.showWarning("添加我为共同作业人", "请确认",
                        new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mPresenter.addCoWorker(UserManager.getInstance().getToken(),
                                        program.getId(), position - 1);
                                mDialogLoader.changeToProgressType("正在提交...");
                            }
                        });
            }

        }, new TroubleProgramAdapter.onItemOperatorListener() {
            @Override
            public void onOperator(final ProgramBean program, String status, final int position) {
                //取消共同作业人
                mDialogLoader.showWarning("取消我为共同作业人", "请确认",
                        new IDialogClickListener() {
                            @Override
                            public void onClick() {

                                mPresenter.cancelCoWorker(UserManager.getInstance().getToken(),
                                        program.getId(), position - 1);
                                mDialogLoader.changeToProgressType("正在提交...");
                            }
                        });
            }
        });
        mProgramAdapter.addHeaderView(LayoutInflater.from(_mActivity).inflate(R.layout.item_head_work_program,
                null));
        mRecyclerViewWorkProgram.setAdapter(mProgramAdapter);
    }

    private void initData() {
        mRecyclerViewPerson.setAdapter(mPersonAdapter =
                new TroubleWorkPersonAdapter(R.layout.item_trouble_work_person, null));
        mRecyclerViewCommonTrouble.setAdapter(mCommonAdapter =
                new TroubleCommonAdapter(R.layout.item_trouble_common, null));
        mRecyclerViewCommonTrouble.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                DiagnoseBean diagnoseBean = (DiagnoseBean) adapter.getItem(position);
                if (diagnoseBean != null) {
                    diagnoseBean.setRepair_id(mRepairId);
                    diagnoseBean.setReference_id(diagnoseBean.getId());
                    diagnoseBean.setRepair_task_id(mRepairTaskId);
                    diagnoseBean.setRepair_phenomenon_id(
                            mTroublePagerAdapter.getTrouble(mCurrentTroubleIndex).getId());
                    diagnoseBean.setTemp(true);
                    diagnoseBean.setManual(false);
                    mTroublePagerAdapter.notifyChange(mCurrentTroubleIndex, diagnoseBean);
                    if (mUiDelegate != null) {
                        mUiDelegate.changeState();
                    }
                }
            }
        });
        mPresenter.getWorkData(UserManager.getInstance().getToken(),
                mRepairId, mVehicleSeriesId);
        addTopView(R.layout.view_loading, mLayoutContainer, 1050, 650);
    }

    @Subscribe
    public void onGoodsEvent(GoodsEvent event) {
        mPresenter.getWorkData(UserManager.getInstance().getToken(),
                mRepairId, mVehicleSeriesId);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onAddProgramEvent(AddProgramEvent event) {
        if (event.mRepairId == mRepairId) {
            mProgramAdapter.addData(0, event.mItemEntity);
            if (mUiDelegate != null) {
                mUiDelegate.changeState();
            }
        }
    }


    public void onConfirmDiagnose() {
        List<DiagnoseBean> list = mTroublePagerAdapter.getTroubleBeans();
        if (list == null || list.isEmpty()) {
            ToastUtils.showShort("请先添加诊断");
        } else {
            mDialogLoader.showProgressDialog(false, "正在提交",
                    "请稍候...");
            mPresenter.confirmDiagnoseList(UserManager.getInstance().getToken(),
                    mRepairId, mRepairTaskId, mVehicleSeriesId,
                    JSON.toJSONString(list));
        }

    }

    public void onDoneWork() {
        if (mProgramAdapter != null) {
            //判断自己是否作业
            List<MultipleItemEntity> programList =
                    mProgramAdapter.getData();
            boolean hasMe = false;
            for (MultipleItemEntity entity : programList) {
                if (entity.getItemType() == TYPE_MANUAL_CONFIRM
                        || entity.getItemType() == TYPE_CAN_NOT_EDIT) {
                    ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                    if (programBean != null) {
                        List<PersonBean> personBeanList = programBean.getPersonList();
                        PersonBean mainPerson = programBean.getMainPerson();
                        if (mainPerson != null) {
                            if (mainPerson.getJob_no().equals(UserManager
                                    .getInstance().getCurrentUserCode())) {
                                hasMe = true;
                            }
                        }
                        if (!hasMe) {
                            if (personBeanList != null) {
                                for (PersonBean personBean : personBeanList) {
                                    if (personBean.getJob_no().equals(UserManager.getInstance().getCurrentUserCode())) {
                                        hasMe = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (hasMe) {
                mDialogLoader.showProgressDialog(false, "正在提交",
                        "请稍后...");
                mPresenter.submitFinishWork(UserManager.getInstance().getToken(),
                        mRepairId,
                        mRepairTaskId,
                        mVehicleSeriesId);
            } else {
                mDialogLoader.showWarning("提示", "您未添加任何作业\n是否继续完成",
                        new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.changeToProgressType("正在提交...");
                                mPresenter.submitFinishWork(UserManager.getInstance().getToken(),
                                        mRepairId,
                                        mRepairTaskId,
                                        mVehicleSeriesId);
                            }
                        });
            }
        }
    }

    @OnClick(R2.id.et_search_trouble)
    public void showSearchDialog() {
        if (mTroublePagerAdapter != null) {
            final RepairTaskBean.FaultPhenomenonListBean current =
                    mTroublePagerAdapter.getTrouble(mCurrentTroubleIndex);
            if (current != null) {
                DialogSearchTrouble dialogSearchTrouble =
                        new DialogSearchTrouble(_mActivity, mRepairId, mRepairTaskId
                                , current.getId(), UserManager.getInstance().getToken(),
                                new OnItemChooseListener<DiagnoseBean>() {
                                    @Override
                                    public void onChoose(DiagnoseBean diagnoseBean) {
                                        mTroublePagerAdapter.notifyChange(mCurrentTroubleIndex, diagnoseBean);
                                        if (mUiDelegate != null) {
                                            mUiDelegate.changeState();
                                        }
                                    }
                                });
                Window dialogWindow = dialogSearchTrouble.getWindow();
                if (dialogWindow != null) {
                    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                    lp.width = ScreenUtils.getScreenWidth(); // 宽度
                    lp.height = WindowManager.LayoutParams.WRAP_CONTENT; // 高度
                    dialogWindow.setGravity(Gravity.TOP);
                    dialogWindow.setAttributes(lp);
                    dialogSearchTrouble.show();
                }
            }
        }
    }

    @Override
    public RepairPresenter getPresenter() {
        return new RepairPresenter(this);
    }

    public void setTroubleData(final ArrayList<RepairTaskBean.FaultPhenomenonListBean> list
            , int status) {
        if (list == null || list.isEmpty()) {
            mTvTroubleCount.setVisibility(View.GONE);
        } else {
            mTvTroubleCount.setText(String.format(Locale.CHINA, "%d/%d",
                    1, list.size()));
            mViewPagerTrouble.setAdapter(mTroublePagerAdapter =
                    new TroublePagerAdapter(_mActivity, status,
                            list, new OnItemChooseListener<DiagnoseBean>() {
                        @Override
                        public void onChoose(DiagnoseBean diagnoseBean) {
                            if (mUiDelegate != null) {
                                mUiDelegate.changeState();
                            }
                        }
                    }
                            , new OnItemChooseListener<DiagnoseBean>() {
                        @Override
                        public void onChoose(final DiagnoseBean diagnoseBean) {
                            mDialogLoader.showWarning("删除诊断", "确认删除么?",
                                    new IDialogClickListener() {
                                        @Override
                                        public void onClick() {
                                            mDialogLoader.changeToProgressType("正在提交");
                                            mPresenter.deleteDiagnose(UserManager.getInstance().getToken(),
                                                    mRepairId, mVehicleSeriesId, diagnoseBean.getId(),
                                                    diagnoseBean.isManual() ? 2 : 1);
                                        }
                                    });
                        }
                    }, new OnItemChooseListener<DiagnoseBean>() {
                        @Override
                        public void onChoose(DiagnoseBean diagnoseBean) {
                            onContactWithOtherProgram(diagnoseBean);
                        }
                    }, new OnItemChooseListener<DiagnoseBean>() {
                        @Override
                        public void onChoose(DiagnoseBean diagnoseBean) {
                            EventBus.getDefault().post(new StartBrotherEvent(
                                    OperationChooseDelegate.newInstance(diagnoseBean, mRepairId
                                    )));
                        }
                    }));
            mViewPagerTrouble.addOnPageChangeListener(
                    mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int i, float v, int i1) {

                        }

                        @Override
                        public void onPageSelected(int i) {
                            mCurrentTroubleIndex = i;
                            mTvTroubleCount.setText(String.format(Locale.CHINA, "%d/%d",
                                    i + 1, list.size()));
                            RepairTaskBean.FaultPhenomenonListBean faultPhenomenonListBean = list.get(i);
                            mCommonAdapter.setNewData(faultPhenomenonListBean.getCommonFaultDiagnosticList());
//                            if (mUiDelegate != null) {
//                                mUiDelegate.changeState();
//                            }
                        }

                        @Override
                        public void onPageScrollStateChanged(int i) {

                        }
                    });
            CommonNavigator commonNavigator = new CommonNavigator(_mActivity);
            commonNavigator.setAdapter(new TroubleAdapter(list,
                    new TroubleAdapter.OnItemChooseListener() {
                        @Override
                        public void onItemChoose(int index, int count) {
                            mViewPagerTrouble.setCurrentItem(index);
                            mTvTroubleCount.setText(String.format(Locale.CHINA, "%d/%d",
                                    index + 1, count));
                            mCurrentTroubleIndex = index;
                            RepairTaskBean.FaultPhenomenonListBean faultPhenomenonListBean =
                                    list.get(index);
                            mCommonAdapter.setNewData(faultPhenomenonListBean.getCommonFaultDiagnosticList());
                        }
                    }));
            mMagicIndicator.setNavigator(commonNavigator);
            if (!list.isEmpty()) {
                mCommonAdapter.setNewData(list.get(0).getCommonFaultDiagnosticList());
            }
        }
    }

    @Override
    public void postDiagnoseList(List<DiagnoseBean> list) {
        mDialogLoader.clearDialog();
        if (mTroublePagerAdapter != null) {
            mTroublePagerAdapter.replaceDiagnose(list);
        }
        if (mProgramAdapter != null) {
            mProgramAdapter.addData(new RepairDataConvert().
                    programToMultipleItemEntity(list, 1));
        }
        if (mUiDelegate != null) {
            mUiDelegate.changeState();
        }
    }

    @Override
    public void showRepairTask(RepairTaskBean repairTaskBean) {
        Log.e("showRepairTask", "showRepairTask");
        if (repairTaskBean != null) {
            mCurrentTroubleIndex = 0;
            mRepairTaskId = repairTaskBean.getId();
            mPersonAdapter.setNewData(repairTaskBean.getWorkerList());
            if (mOnPageChangeListener != null) {
                mViewPagerTrouble.removeOnPageChangeListener(mOnPageChangeListener);
            }
            int status = repairTaskBean.getMy_status();
            mStatus = status;
            if (mOperationState == 0) {
                status = 100;
                mTvConfirm.setVisibility(View.GONE);
            }
            setTroubleData(repairTaskBean.getFaultPhenomenonList(), status);
            mProgramAdapter.setNewData(new RepairDataConvert().
                    programToMultipleItemEntity(repairTaskBean));
            removeTopView(mLayoutContainer);
            mUiDelegate = new UiDelegate(_mActivity, mTroublePagerAdapter, mEtSearch,
                    mTvCommonDiagnose, mRecyclerViewCommonTrouble, mCommonAdapter,
                    mTvWorkProgram, mRecyclerViewWorkProgram, mProgramAdapter, mTvConfirm);
            mUiDelegate.changeState();
            mUiDelegate.init(status);
            changeTroubleCount(repairTaskBean.getFaultPhenomenonList());
        }
    }

    public void changeTroubleCount(ArrayList<RepairTaskBean.FaultPhenomenonListBean>
                                           faultPhenomenonList) {
        WorkDelegate workDelegate = (WorkDelegate) getParentFragment();
        if (workDelegate != null) {
            workDelegate.changeTroubleCount(getUnResolveCount(faultPhenomenonList),
                    mPosition);
        }
    }

    private int getUnResolveCount(List<RepairTaskBean.FaultPhenomenonListBean>
                                          faultPhenomenonList) {
        int count = 0;
        if (faultPhenomenonList != null && !faultPhenomenonList.isEmpty()) {
            for (RepairTaskBean.FaultPhenomenonListBean faultPhenomenonListBean :
                    faultPhenomenonList) {
                ArrayList<DiagnoseBean> diagnoseBeans =
                        faultPhenomenonListBean.getFaultDiagnosticTemporaryList();
                if (diagnoseBeans == null || diagnoseBeans.isEmpty()) {

                    count++;
                } else {
                    for (DiagnoseBean diagnoseBean : diagnoseBeans) {
                        if (diagnoseBean.getPlanList() == null ||
                                diagnoseBean.getPlanList().isEmpty()) {
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }

    @Override
    public void showError(String msg) {
        mDialogLoader.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void deleteDiagnoseSucceed() {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDialogLoader.stopProgressWithSuccess("删除成功", null, new IDialogClickListener() {
                    @Override
                    public void onClick() {
                        mDialogLoader.clearDialog();
                    }
                });
            }
        });
    }

    @Override
    public void deleteProgramSucceed(final int position) {
        mDialogLoader.stopProgressWithSuccess("删除成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                if (mProgramAdapter != null) {
                    MultipleItemEntity entity = mProgramAdapter.getItem(position);
                    if (entity != null) {
                        ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                        //找到删除的哪一个数据，做本地删除
                        if (mTroublePagerAdapter.getData() != null && programBean != null) {
                            for (RepairTaskBean.FaultPhenomenonListBean faultPhenomenonListBean :
                                    mTroublePagerAdapter.getData()) {
                                if (faultPhenomenonListBean.getId() == programBean.getPhenomenon_id()) {
                                    List<DiagnoseBean> diagnoseBeans =
                                            faultPhenomenonListBean.getFaultDiagnosticTemporaryList();
                                    if (diagnoseBeans != null) {
                                        for (DiagnoseBean diagnoseBean : diagnoseBeans) {
                                            if (diagnoseBean.getId() == programBean.getFault_diagnostic_id()) {
                                                List<ProgramBean> programBeans = diagnoseBean.getPlanList();
                                                if (programBeans != null) {
                                                    if (programBeans.remove(programBean)) {
                                                        WorkDelegate workDelegate =
                                                                (WorkDelegate) getParentFragment();
                                                        if (workDelegate != null) {
                                                            workDelegate.changeTroubleCount
                                                                    (getUnResolveCount(mTroublePagerAdapter.getData()),
                                                                            mPosition);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        mProgramAdapter.remove(position);
                    }
                    if (mUiDelegate != null) {
                        mUiDelegate.changeState();
                    }
                }
                mDialogLoader.clearDialog();
            }
        });

    }

    @Override
    public void showPickGoods(final PickGoodsWrapper pickGoodsWrapper) {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (pickGoodsWrapper != null) {
                    List<PickGoods> list = pickGoodsWrapper.getApplyMaterials();
                    if (list != null && !list.isEmpty()) {
                        mDialogLoader.clearDialog();
                        DialogConfirmProgram dialogDeleteProgram = new DialogConfirmProgram(_mActivity,
                                list,
                                new OnItemChooseListener<String>() {
                                    @Override
                                    public void onChoose(String o) {
                                        //发起领料
                                        mDialogLoader.showProgressDialog(true,
                                                "正在提交", "请稍候...");
                                        mPresenter.pickGoods(UserManager.getInstance().getToken(), mRepairId,
                                                mVehicleSeriesId,
                                                o);
                                    }
                                });
                        Window dialogWindow = dialogDeleteProgram.getWindow();
                        if (dialogWindow != null) {
                            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
                            lp.height = ScreenUtils.getScreenHeight() * 820 / 1024; // 高度
                            dialogWindow.setGravity(Gravity.CENTER);
                            dialogWindow.setAttributes(lp);
                            dialogDeleteProgram.show();
                        }
                    } else {
                        mDialogLoader.stopProgressWithSuccess("方案提交成功", null,
                                new IDialogClickListener() {
                                    @Override
                                    public void onClick() {
                                        mDialogLoader.clearDialog();
                                    }
                                });
                    }
                } else {
                    mDialogLoader.stopProgressWithSuccess("方案提交成功", null,
                            new IDialogClickListener() {
                                @Override
                                public void onClick() {
                                    mDialogLoader.clearDialog();
                                }
                            });
                }
            }
        });

    }

    @Override
    public void submitFinishSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                EventBus.getDefault().post(new ReloadRepairWorkDataEvent(mRepairId));
            }
        });
    }

    @Override
    public void finishSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
            }
        });
    }

    @Override
    public void pickGoodsSucceed() {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDialogLoader.stopProgressWithSuccess("申请已提交",
                        "可在[我的领料单]中查看审批进度",
                        new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();
                                EventBus.getDefault().post(
                                        new StartBrotherEvent
                                                (GoodsOrderDelegate.newInstance(mRepairId)));
                            }
                        });
                mDialogLoader.setConfirmText("查看我的领料单");
                mDialogLoader.showCancel(true);
            }
        });
    }

    @Override
    public void returnGoodsSucceed(int position) {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDialogLoader.stopProgressWithSuccess("退料成功", null,
                        new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();
                            }
                        });
            }
        });
        if (mProgramAdapter != null) {
            MultipleItemEntity entity = mProgramAdapter.getItem(position);
            if (entity != null) {
                ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                if (programBean != null) {
                    //退料中
                    programBean.setPicking_status(6);
                    mProgramAdapter.notifyItemChanged(position + 1);
                }
            }
        }
    }

    @Override
    public void troubleHadDelete(String msg) {
        mDialogLoader.stopProgressWithFailed("提交失败", msg, new IDialogClickListener() {
            @Override
            public void onClick() {
                mPresenter.getWorkData(UserManager.getInstance().getToken(),
                        mRepairId, mVehicleSeriesId);
            }
        });
    }

    @Override
    public void addCoWorkerSucceed(final int position) {
        mDialogLoader.stopProgressWithSuccess("添加成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                if (mProgramAdapter != null) {
                    MultipleItemEntity entity = mProgramAdapter.getItem(position);
                    if (entity != null) {
                        final ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                        List<PersonBean> list = programBean.getPersonList();
                        if (list == null) {
                            list = new ArrayList<>();
                            programBean.setPersonList(list);
                        }
                        list.add(new PersonBean(UserManager.getInstance()
                                .getCurrentUserName(),
                                UserManager.getInstance().getCurrentUserCode()));
                        mProgramAdapter.notifyItemChanged(position + 1);
                    }
                }
                mDialogLoader.clearDialog();
            }
        });
    }

    @Override
    public void cancelCoWorkerSucceed(final int position) {
        mDialogLoader.stopProgressWithSuccess("取消成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                if (mProgramAdapter != null) {
                    MultipleItemEntity entity = mProgramAdapter.getItem(position);
                    if (entity != null) {
                        final ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                        List<PersonBean> list = programBean.getPersonList();
                        if (list != null) {
                            int index = -1;
                            for (int i = 0, size = list.size(); i < size; i++) {
                                PersonBean personBean = list.get(i);
                                if (personBean.getJob_no().equals(UserManager.
                                        getInstance().getCurrentUserCode())) {
                                    index = i;
                                    break;
                                }
                            }
                            if (index != -1) {
                                list.remove(index);
                                mProgramAdapter.notifyItemChanged(position + 1);
                            }
                        }
                    }
                }
                mDialogLoader.clearDialog();
            }
        });
    }

    @Override
    public void cancelFinishWorkSucceed() {
        _mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDialogLoader.stopProgressWithSuccess("取消成功",
                        "请确认", new IDialogClickListener() {
                            @Override
                            public void onClick() {
                                mDialogLoader.clearDialog();
                            }
                        });
            }
        });
    }

    /**
     * 选择动作
     */
    private void chooseAction(final BaseQuickAdapter adapter, final View view, final int position) {
        new DialogActionChoose(_mActivity, GlobalDataManager.getInstance().getOperationBeans(),
                new OnItemChooseListener<OperationBean>() {

                    @Override
                    public void onChoose(OperationBean operationBean) {
                        Log.e("onChoose", position + "");
                        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                        if (entity != null) {
                            ProgramBean diagnoseBean = entity.getField(ItemFields.ITEM_OBJ);
                            diagnoseBean.setAction_name(operationBean.getAction_name());
                            diagnoseBean.setMaintenance_action_id(operationBean.getId());
                            ((TextView) view).setText(operationBean.getAction_name());
//                            adapter.notifyItemChanged(position);
                        }
                    }
                }).show();
    }

    /**
     * 选择零部件和编码
     */
    private void choosePart(final BaseQuickAdapter adapter, final View view, final int position,
                            final boolean isPart) {
        DialogPartChoose dialogPartChoose = new DialogPartChoose(_mActivity, mRepairId,
                new OnItemChooseListener<PartBean>() {
                    @Override
                    public void onChoose(PartBean partBean) {
                        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                        if (entity != null) {
                            ProgramBean diagnoseBean = entity.getField(ItemFields.ITEM_OBJ);
                            TextView tv = ((TextView) view);
                            if (isPart) {
                                diagnoseBean.setPart(partBean);
                                if (view.getId() == R.id.tv_obj) {
                                    //零件
                                    tv.setText(partBean.getMaterial_name());
                                    TextView tvCode = (TextView) adapter.getViewByPosition(mRecyclerViewWorkProgram,
                                            position + 1, R.id.tv_part_code);
                                    if (tvCode != null) {
                                        tvCode.setText(partBean.getMaterial_no());
                                    }
                                } else {
                                    //编号
                                    tv.setText(partBean.getMaterial_no());
                                    TextView tvName = (TextView) adapter.getViewByPosition(mRecyclerViewWorkProgram,
                                            position + 1, R.id.tv_obj);
                                    if (tvName != null) {
                                        tvName.setText(partBean.getMaterial_name());
                                    }
                                }
                                TextView tvUnit = (TextView) adapter.getViewByPosition(mRecyclerViewWorkProgram,
                                        position + 1, R.id.tv_unit);
                                if (tvUnit != null) {
                                    tvUnit.setText(partBean.getUnit() == null ? "无" : partBean.getUnit());
                                }
                            } else {
                                diagnoseBean.setMaterial(partBean);
                                if (view.getId() == R.id.tv_materials) {
                                    //耗材
                                    tv.setText(partBean.getMaterial_name());
                                    TextView tvCode = (TextView) adapter.getViewByPosition(mRecyclerViewWorkProgram,
                                            position + 1, R.id.tv_materials_code);
                                    if (tvCode != null) {
                                        tvCode.setText(partBean.getMaterial_no());
                                    }
                                } else {
                                    //编号
                                    tv.setText(partBean.getMaterial_no());
                                    TextView tvName = (TextView) adapter.getViewByPosition(mRecyclerViewWorkProgram,
                                            position + 1, R.id.tv_materials);
                                    if (tvName != null) {
                                        tvName.setText(partBean.getMaterial_name());
                                    }
                                }
                            }
                        }
                    }
                }, isPart);
        Window dialogWindow = dialogPartChoose.getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
            lp.height = ScreenUtils.getScreenHeight() * 720 / 1024; // 高度
            dialogWindow.setGravity(Gravity.CENTER);
            dialogWindow.setAttributes(lp);
            dialogPartChoose.show();
        }
    }

    /**
     * 零部件输入选择
     */
    private void choosePartCount(final BaseQuickAdapter adapter, final View view, final int position) {
        pvCustomOptions = new OptionsPickerBuilder(_mActivity,
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                        if (entity != null) {
                            ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                            if (programBean != null) {
                                PartBean partBean = programBean.getPart();
                                if (partBean != null) {
                                    partBean.setVal(options1 + 1);
                                    ((TextView) view).setText(String.format(
                                            Locale.CHINA, "%d", options1 + 1));
                                } else {
                                    ToastUtils.showShort("请先选择对象");
                                }
                            }
                        }
                    }
                })
                .setLayoutRes(R.layout.dialog_number_select, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        v.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptions.dismiss();
                            }
                        });
                        v.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomOptions.returnData();
                                pvCustomOptions.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();
        List<PickNumberBean> list = new ArrayList<>();
        for (int i = 1; i < 50; i++) {
            list.add(new PickNumberBean(i + ""));
        }
        //noinspection unchecked
        pvCustomOptions.setPicker(list);//添加数据
        pvCustomOptions.show();
    }

    /**
     * 耗材数量选择
     */
    private void chooseGoodsCount(BaseQuickAdapter adapter, final View view, int position) {
        MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
        if (entity != null) {
            ProgramBean diagnoseBean = entity.getField(ItemFields.ITEM_OBJ);
            final PartBean partBean = diagnoseBean.getMaterial();
            if (partBean == null) {
                ToastUtils.showShort("请先选择耗材");
            } else {
                DialogNumberSelect dialogGoodsCount = new DialogNumberSelect(_mActivity,
                        new OnItemChooseListener<String>() {
                            @Override
                            public void onChoose(String s) {
                                partBean.setVal(Integer.parseInt(s));
                                ((TextView) view).setText(String.format("%s%s", s, partBean.getUnit() == null ? "L" :
                                        partBean.getUnit()));
                            }
                        });
                Window dialogWindow = dialogGoodsCount.getWindow();
                if (dialogWindow != null) {
                    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                    lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
                    lp.height = ScreenUtils.getScreenHeight() * 420 / 1024; // 高度
                    dialogWindow.setGravity(Gravity.CENTER);
                    dialogWindow.setAttributes(lp);
                    dialogGoodsCount.show();
                }
            }
        }
    }

    /**
     * 位置选择
     *
     * @param adapter
     * @param view
     * @param position
     */
    private void choosePartLocation(final BaseQuickAdapter adapter, final View view, final int position) {
        new DialogPartLocationChoose(_mActivity,
                new DialogPartLocationChoose.OnLocationChooseListener() {

                    @Override
                    public void onChoose(PartLocationBean partLocationBean, String temp) {
                        if (temp.isEmpty()) {
                            //没有临时添加的位置
                            MultipleItemEntity entity = (MultipleItemEntity) adapter.getItem(position);
                            if (entity != null) {
                                ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
                                programBean.setPositionName(partLocationBean.getPositionName());
                                programBean.setPositionCode(partLocationBean.getPositionCode());
                                //diagnoseBean.setAction_name(operationBean.getAction_name());
                                // diagnoseBean.setMaintenance_action_id(operationBean.getId());
                                ((TextView) view).setText(partLocationBean.getPositionName());
                            }
                        } else {
                            //有临时添加的位置
                            mDialogLoader.showProgressDialog(false, "正在添加",
                                    "请稍候...");
                            mPresenter.addTempLocation(UserManager.getInstance().getToken(),
                                    position, partLocationBean, temp);

                        }

                    }
                }).measureSize().show();
    }

    /**
     * 删除方案
     */
    private void deleteProgram(final ProgramBean programBean, final int position) {
//        DialogDeleteProgram dialogDeleteProgram = new DialogDeleteProgram(_mActivity,
//                programBean,
//                new OnItemChooseListener<Object>() {
//                    @Override
//                    public void onChoose(Object o) {
        mDialogLoader.changeToProgressType("正在提交...");
        mPresenter.deleteProgram(UserManager.getInstance().getToken(),
                mRepairId, programBean.getFault_diagnostic_id(),
                programBean.getId(), position);
//                    }
//                });
//        Window dialogWindow = dialogDeleteProgram.getWindow();
//        if (dialogWindow != null) {
//            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
//            lp.height = ScreenUtils.getScreenHeight() * 820 / 1024; // 高度
//            dialogWindow.setGravity(Gravity.CENTER);
//            dialogWindow.setAttributes(lp);
//            dialogDeleteProgram.show();
//        }
    }

    /**
     * 退料
     */
    public void returnGoods(final ProgramBean programBean, final int position) {
        mDialogLoader.changeToProgressType("正在提交...");
        mPresenter.returnGoods(UserManager.getInstance().getToken(),
                "", programBean.getId(), position);

    }

    public void onContactWithOtherProgram(DiagnoseBean diagnoseBean) {
        DialogContactOtherProgram dialogContactOtherProgram =
                new DialogContactOtherProgram(_mActivity,
                        new OnItemChooseListener<List<MultipleItemEntity>>() {
                            @Override
                            public void onChoose(List<MultipleItemEntity> programBeans) {
                                if (mProgramAdapter != null) {
                                    mProgramAdapter.addData(0, programBeans);
                                    if (mUiDelegate != null) {
                                        mUiDelegate.changeState();
                                    }
                                }
                            }
                        }, mRepairId, diagnoseBean);
        dialogContactOtherProgram.setCanceledOnTouchOutside(false);
        Window dialogWindow = dialogContactOtherProgram.getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth() * 1000 / 1280; // 宽度
            lp.height = ScreenUtils.getScreenHeight() * 820 / 1024; // 高度
            dialogWindow.setGravity(Gravity.CENTER);
            dialogWindow.setAttributes(lp);
            dialogContactOtherProgram.show();
        }
    }

    /**
     * 提交方案
     */
    public void onProgramConfirm() {
        if (!mProgramAdapter.getData().isEmpty()) {
//            if (mProgramAdapter.hasNoPart()) {
//                ToastUtils.showShort("您还有未添加对象的方案!");
//            } else {
            mDialogLoader.showProgressDialog(false, "正在提交", "请稍候...");
            mPresenter.confirmProgram(UserManager.getInstance().getToken(),
                    mRepairId, mRepairTaskId, mVehicleSeriesId,
                    new RepairDataConvert().programListToJson(mProgramAdapter.getData(),
                            mRepairId,
                            mVehicleSeriesId, 1));
            //      }
        } else {
            ToastUtils.showShort("请先添加方案");
        }

    }

    @Override
    public void showTempLocation(PartLocationBean partLocationBean, int position) {
        mDialogLoader.clearDialog();
        MultipleItemEntity entity = mProgramAdapter.getItem(position);
        if (entity != null) {
            ProgramBean programBean = entity.getField(ItemFields.ITEM_OBJ);
            programBean.setPositionName(partLocationBean.getPositionName());
            programBean.setPositionCode(partLocationBean.getPositionCode());
            mProgramAdapter.notifyItemChanged(position + 1);
        }
    }

    private void onWorkCancel() {
        mDialogLoader.showProgressDialog(false, "正在提交",
                "请稍候...");
        mPresenter.cancelFinishWork(UserManager.getInstance().getToken(),
                mRepairId, mRepairTaskId, mVehicleSeriesId);
    }

    @OnClick(R2.id.tv_confirm)
    public void onConfirm() {
        if (mUiDelegate != null) {
            switch (mUiDelegate.getSTATE()) {
                case CONFIRM_DIAGNOSE:
                    onConfirmDiagnose();
                    break;
                case CONFIRM_PROGRAM:
                    onProgramConfirm();
                    break;
                case WORK_DONE:
                    onDoneWork();
                    break;
                case WORK_CANCEL:
                    onWorkCancel();
                    break;
            }
        }
    }
}
